package com.xuxin.baby.fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.base.BaseFragment;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UploadFilesBean;
import com.xuxin.baby.contract.ChildEatingRecordContract;
import com.xuxin.baby.contract.UploadFilesContract;
import com.xuxin.baby.event.BaseEventFragment;
import com.xuxin.baby.event.EatingHelpEvent;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.photo.PhotoUtils;
import com.xuxin.baby.presenter.ChildEatingRecordPresenter;
import com.xuxin.baby.presenter.UploadFilesPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.PathUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by xu_xin
 * Created on 2020.08.17 0017
 * 记喂养 -> 辅食
 */
public class ChildEatingHelpFragment extends BaseEventFragment implements ChildEatingRecordContract.View, UploadFilesContract.View {
    private final ChildEatingRecordContract.Presenter presenter = new ChildEatingRecordPresenter(this);
    private final UploadFilesContract.Presenter presenter2 = new UploadFilesPresenter(this);
    @BindView(R.id.child_eating_help_mark)
    EditText child_eating_help_mark;//随手记
    @BindView(R.id.child_eating_help_image)
    ImageView child_eating_help_image;

    private String tenantId;//租户id
    private String token;//授权token
    private String childId;//宝宝ID
    private String mark;//	辅食记录内容
    private String picture;//上传图片

    public static ChildEatingHelpFragment newInstance() {
        return new ChildEatingHelpFragment();
    }

    @Override
    public View setContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_child_eating_help, container, false);
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(getContext());
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        childId = aCache.getAsString(BaseConstant.childId);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.child_eating_help_image})
    public void onClick(View view) {
        if (view.getId() == R.id.child_eating_help_image) {
            PhotoUtils.openPhoto(getContext(), new PhotoUtils.OnResultListener() {
                @Override
                public void onResult(List<LocalMedia> result) {
                    takePhoto(result);
                }
            });
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://上传照片
                    presenter2.uploadFiles(tenantId, token, childId, "Edu_EventFeed", "pic1", parts);
                    break;
                case 1://记录辅食
                    presenter.recordHelp(tenantId, token, childId, TimeUtils.getNowString(), mark, picture);
                    break;
            }
            return false;
        }
    });


    @Override
    public void onSuccess(BaseBean baseBean) {
        requireActivity().finish();
        ToastUtils.showShort("保存成功");
    }

    @Override
    public void onSuccess(UploadFilesBean uploadFilesBean) {
        picture = uploadFilesBean.getResult();
        handler.sendEmptyMessage(1);
    }

    private List<MultipartBody.Part> parts;

    public void takePhoto(List<LocalMedia> result) {
        LocalMedia media = result.get(0);
        String path = media.isCompressed() ? media.getCompressPath() : media.getPath();
        GlideApp.with(this).load(path).centerCrop().into(child_eating_help_image);
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        parts = new ArrayList<>();
        parts.add(MultipartBody.Part.createFormData("files", PathUtils.getImageName(), requestBody));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EatingHelpEvent event) {
        LogUtils.e("记喂养 -> 辅食 ");
        try {
            mark = child_eating_help_mark.getText().toString();
            if (StringUtils.isEmpty(mark)) {
                ToastUtils.showShort("请输入记录内容");
            } else if (null != parts && parts.size() > 0) {
                popup.show();
                handler.sendEmptyMessage(0);//上传照片
            } else {
                popup.show();
                handler.sendEmptyMessage(1);//记录辅食
            }
        } catch (Exception e) {
            e.printStackTrace();
            dismiss();
        }
    }
}